{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 使用Syft Keras进行隐私预测"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 1: 公开训练\n",
    "\n",
    "欢迎使用本教程！ 在以下笔记本中，您将学习如何提供隐私预测。隐私预测是指在整个过程中对数据进行持续加密。用户绝不会共享原始数据，而只会共享加密（即秘密共享）的数据。为了提供这些私人预测，Syft Keras在后台使用了一个名为[TF Encrypted](https://github.com/tf-encrypted/tf-encrypted)的库。 TF Encrypted结合了最先进的加密技术和机器学习技术，但您不必为此担心，可以专注于您的机器学习应用程序。\n",
    "\n",
    "您只需三个步骤即可开始提供隐私预测：\n",
    "- **步骤1**: 使用普通的Keras训练模型。\n",
    "- **步骤2**：保护并服务您的机器学习模型（服务器）。\n",
    "- **步骤3**：查询安全模型以接收私有预测（客户端）。\n",
    "\n",
    "好吧，让我们完成这三个步骤，以便您可以在不牺牲用户隐私或模型安全性的情况下部署有效的机器学习服务。\n",
    "\n",
    "作者:\n",
    "- Jason Mancuso - Twitter: [@jvmancuso](https://twitter.com/jvmancuso)\n",
    "- Yann Dupis - Twitter: [@YannDupis](https://twitter.com/YannDupis)\n",
    "- Morten Dahl - Twitter: [@mortendahlcs](https://github.com/mortendahlcs)\n",
    "\n",
    "代表:\n",
    "- Dropout Labs - Twitter: [@dropoutlabs](https://twitter.com/dropoutlabs)\n",
    "- TF Encrypted - Twitter: [@tf_encrypted](https://twitter.com/tf_encrypted)\n",
    "\n",
    "中文版译者：\n",
    "- Hou Wei - github：[@dljgs1](https://github.com/dljgs1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 使用Keras训练你的模型"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "要为您的项目使用保护隐私的机器学习技术，您不必学习新的机器学习框架。 如果您具有基本的[Keras](https://keras.io/)知识，则可以将这些技术与Syft Keras一起使用。 如果您以前从未使用过Keras，则可以通过[Keras文档](https://keras.io)了解更多有关Keras的信息。\n",
    "\n",
    "在提供私人预测之前，第一步是使用普通Keras训练模型。 例如，我们将训练一个模型来对手写数字进行分类。 为了训练该模型，我们将使用规范的[MNIST数据集](http://yann.lecun.com/exdb/mnist/)。\n",
    "\n",
    "我们从参考Keras存储库中借用了[此示例](https://github.com/keras-team/keras/blob/master/examples/mnist_cnn.py)。 要训练您的分类模型，只需运行下面的单元格。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import tensorflow.keras as keras\n",
    "from tensorflow.keras.datasets import mnist\n",
    "from tensorflow.keras.models import Sequential\n",
    "from tensorflow.keras.layers import Dense, Dropout, Flatten\n",
    "from tensorflow.keras.layers import Conv2D, AveragePooling2D\n",
    "from tensorflow.keras.layers import Activation\n",
    "\n",
    "batch_size = 128\n",
    "num_classes = 10\n",
    "epochs = 2\n",
    "\n",
    "# input image dimensions\n",
    "img_rows, img_cols = 28, 28\n",
    "\n",
    "# the data, split between train and test sets\n",
    "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n",
    "\n",
    "x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)\n",
    "x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)\n",
    "input_shape = (img_rows, img_cols, 1)\n",
    "\n",
    "x_train = x_train.astype('float32')\n",
    "x_test = x_test.astype('float32')\n",
    "x_train /= 255\n",
    "x_test /= 255\n",
    "print('x_train shape:', x_train.shape)\n",
    "print(x_train.shape[0], 'train samples')\n",
    "print(x_test.shape[0], 'test samples')\n",
    "\n",
    "# convert class vectors to binary class matrices\n",
    "y_train = keras.utils.to_categorical(y_train, num_classes)\n",
    "y_test = keras.utils.to_categorical(y_test, num_classes)\n",
    "\n",
    "model = Sequential()\n",
    "\n",
    "model.add(Conv2D(10, (3, 3), input_shape=input_shape))\n",
    "model.add(AveragePooling2D((2, 2)))\n",
    "model.add(Activation('relu'))\n",
    "model.add(Conv2D(32, (3, 3)))\n",
    "model.add(AveragePooling2D((2, 2)))\n",
    "model.add(Activation('relu'))\n",
    "model.add(Conv2D(64, (3, 3)))\n",
    "model.add(AveragePooling2D((2, 2)))\n",
    "model.add(Activation('relu'))\n",
    "model.add(Flatten())\n",
    "model.add(Dense(num_classes, activation='softmax'))\n",
    "\n",
    "model.compile(loss=keras.losses.categorical_crossentropy,\n",
    "              optimizer=keras.optimizers.Adam(),\n",
    "              metrics=['accuracy'])\n",
    "\n",
    "model.fit(x_train, y_train,\n",
    "          batch_size=batch_size,\n",
    "          epochs=epochs,\n",
    "          verbose=1,\n",
    "          validation_data=(x_test, y_test))\n",
    "score = model.evaluate(x_test, y_test, verbose=0)\n",
    "print('Test loss:', score[0])\n",
    "print('Test accuracy:', score[1])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 保存模型的权重以用于将来的隐私预测"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "好！您的模型已经过训练。让我们使用model.save()保存模型权重。在下一个笔记本中，我们将把这些权重加载到Syft Keras中，以开始提供私人预测。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model.save('short-conv-mnist.h5')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autoclose": false,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
